package com.oe.gateway.filters;

import java.util.concurrent.atomic.LongAdder;

public class IpItem {


    private  long rate;

    private  long internal;

    private long lastResetTime;

    private LongAdder token;

    public IpItem(long rate, long internal) {
        this.rate = rate;
        this.internal = internal;
        this.lastResetTime=now();
        this.token=buildLongAdder(rate);

    }

    public  boolean isAllow(){
        if(now()>lastResetTime+internal){
            this.lastResetTime=now();
            this.token=buildLongAdder(rate);
        }
        if(token.sum()<0){
            return false;
        }
        this.token.decrement();
        return true;
    }


    private long now(){
        return  System.currentTimeMillis();
    }


    private LongAdder buildLongAdder(long rate){
        LongAdder adder = new LongAdder();
        adder.add(rate);
        return adder;
    }
}
